<template>
	<view>
		
		<uni-notice-bar show-icon color="#2979FF" background-color="#EAF2FF"
		scrollable="true" single="true" :text="noticeText" 
		showIcon="true" :speed="30">
		</uni-notice-bar>
		
		<view class="href">
			<view class="box">
				<view class="cu-bar bg-white">
					<view class="action">
						<text class="cuIcon-titles text-blue"></text>
						<text class="text-lg">输入视频或图集链接</text>
					</view>
					<view class="text-blue" style="margin-right: 20px;" @click="getClipboardData">粘贴链接</view>
				</view>
				
			</view>
			
			<view class="input">
				<uni-forms>
					<uni-easyinput type="textarea" v-model="videoSrc" placeholder="输入视频或图集链接" />
				</uni-forms>
			</view>
			
			<view class="padding flex flex-direction">
				<button class="cu-btn bg-blue margin-tb-sm lg" @click="parseClick">去水印解析</button>
			</view>
		</view>
		
		<view class="grid col-2 padding-sm" v-if="resultObj.type == 'video'">
			<video class="video image-self"  :enable-progress-gesture="false"
			mode="aspectFill"  :src="resultObj.videoSrc">
			</video>
			<view class="margin-tb-sm text-center">
				<button class="cu-btn round  bg-gradual-purple text-white button-guoshao" data-type="1" @click="copyContent">复制无水印链接</button>
			</view>
			<view class="margin-tb-sm text-center">
				<button class="cu-btn round  bg-gradual-pink text-white button-guoshao" @click="downFile" data-type="1">保存视频</button>
			</view>
			<view class=" text-center">
				<button class="cu-btn round  bg-gradual-orange text-white button-guoshao" data-type="2" @click="copyContent">复制封面链接</button>
			</view>
			<view class=" text-center">
				<button class="cu-btn round  bg-gradual-green text-white button-guoshao" @click="downFile" data-type="2">保存封面</button>
			</view>
		</view>
		
		<view v-if="resultObj.type == 'video'">
			<view class=" flex flex-direction" style="padding: 10rpx;">
				<button class="cu-btn bg-cyan  lg" data-type="3" @click="copyContent">复制文案</button>
			</view>
			<!-- <view class=" flex flex-direction" style="padding: 10rpx;">
				<button class="cu-btn bg-gradual-red  lg" @click="parseClick">下载通道二(保存失败时使用)</button>
			</view> -->
		</view>
		
		<!-- #ifdef MP-WEIXIN -->
		<ad :unit-id="setAD.banner" ad-intervals="30" v-if="setAD.banner"></ad>
		<!-- #endif -->
		
	</view>
</template>

<script>
	let rewardedVideoAd = null;
		
	let setinad = null;
	
	const constant = require('../../utils/constants.js');
		
	const http = require('../../utils/http.js');
	
	const util = require('../../utils/util.js');
	
	export default {
		data() {
			return {
				setAD:null,
				noticeText:'漫漫去水印免费且不限次数使用',
				videoSrc:'',
				resultObj:{},
				domain:[],
				baseInfo: {}
			}
		},
		onShareAppMessage(res) {
			let that = this;
			return {
				title: '抖音、快手、短视频一键去水印，去水印就是这样简单',
				path: '/pages/index/index',
				imageUrl:'../../static/images/yaoqing.jpg'
			}
		},
		onLoad(options) {
			this.videoSrc = uni.getStorageSync(constant.CACHE_PARSE_URL);
			this.parseVodei();
			this.loadNotice();
			
			let that = this;
			util.getAD(that, function () {
				that.setInterstitialAd(); //加载插屏广告
				that.loadInterstitialAd();
			});
		},
		onHide(){
			clearInterval(setinad);
		},
		methods: {
			getClipboardData:function(){
				let that = this;
				uni.getClipboardData({
					success: function (res) {
						console.log(res.data);
						uni.hideToast();
						that.videoSrc = res.data;
					},fail(err) {
						console.log(err)
					}
				});
			},
			// 获取小程序插屏广告
			setInterstitialAd: function () {
			    var that = this;
			    if (that.setAD.interstitialid && uni.createInterstitialAd) {
			        let interstitialAd = uni.createInterstitialAd({
			            adUnitId: that.setAD.interstitialid
			        }); // 监听插屏错误事件
			
			        interstitialAd.onError((err) => {
			            console.error(err);
			        }); // 显示广告
			
					  if (interstitialAd) {
						if (that.setAD.switch_inad == 'yes') {
						  setinad = setInterval(() => {
							interstitialAd.show().catch(err => {
							  console.error(err);
							});
						  }, 2000);
						} else {
						  setTimeout(() => {
							interstitialAd.show().catch(err => {
							  console.error(err);
							});
						  }, 6000);
						}
					  }
			    }
			},
			parseClick:function(e){
				if(this.videoSrc == '' || this.videoSrc == null){
					uni.showToast({
						title:'请输入解析链接',
						icon:'none'
					})
					return;
				}
				
				let videoSrc = this.videoSrc;
				this.parseVodei();
			},
			parseVodei:function(){
				console.log(this.videoSrc)
				if(this.videoSrc == '' || this.videoSrc == undefined){
					return;
				}
				var that = this;
				
				let data = {
						url : that.videoSrc
					};
				
				uni.showLoading({
					title:'解析中'
				})	
				var params = {
				    url: '/video/parse',
				    method: 'POST',
				    data: data,
				    callBack: function (res) {
				        if(res.code ==  200){
							if(res.data.videoVo.type == 'images'){
								uni.navigateTo({
									url:'../images/images?videoSrc='+that.videoSrc
								})
							}else{
								that.resultObj = res.data.videoVo;
							}
							that.domain = res.data.downDomain;
							that.baseInfo = res.data.baseInfo;
							uni.hideLoading();
						}else{
							uni.showToast({
								title:res.msg,
								icon:'none'
							})
						}
						uni.removeStorageSync(constant.CACHE_PARSE_URL)
				    }
				};
				http.request(params);
			},
			
			loadNotice:function(){
				
				var params = {
				    url: '/notice/getNotice',
				    method: 'get',
				    data: {},
				    callBack: function (res) {
				        if(res.code ==  200){
							this.noticeText = res.data.title;
						}
				    }
				};
				http.request(params);
			},
			copyContent:function(e){
				
				let type = e.currentTarget.dataset.type;
				
				let content = '';
				if(type == 1){
					content = this.resultObj.videoSrc;
				}else if(type == 2){
					content = this.resultObj.coverSrc;
				}else if(type == 3){
					content = this.resultObj.copywriting;
				}
				
				uni.setClipboardData({
				    data: content,
				    success: function (res) {
				        uni.showToast({
				            title: '内容复制成功',
				            duration: 2000,
							icon:'none',
				            success(res) {},
				        
				            fail(res) {}
				        });
				    }
				});
			},
			
			saveVideo:function(filePath){
				let that = this;
				uni.saveVideoToPhotosAlbum({
					filePath: filePath,
					success: function(data) {
						//执行设置缓存方法
						uni.showToast({
							title: '保存成功',
							icon: "success",
							duration: 3000,
							success() {
								
							}
						});
					}
				});
			},
			/**
			 * @param {Object} e视频
			 */
			saveNoMarkVideo:function(e){
				let that = this; 
				let link = this.domain[0].value + this.resultObj.videoSrc;
				console.log(link);
				uni.showLoading({
					title: '下载中',
					duration: 4000
				});
				
				let fileName = new Date().valueOf();
				
				let  sysPath = wx.env.USER_DATA_PATH + '/' + fileName + '.mp4';

				uni.downloadFile({
					url: link,
					filePath: sysPath,
					success: res => {
						//let filePath = res.tempFilePath;
						let filePath = res.filePath;
						uni.saveVideoToPhotosAlbum({
							filePath:filePath,
							success: file => {
								uni.showToast({
									title: '下载成功',
									icon: "success",
									duration: 3000,
									success() {
										
									}
								});
							},
							fail: err => {
								//取消下载
								if ("saveVideoToPhotosAlbum:fail cancel" === err.errMsg) {
									uni.hideLoading();
									return;
								}
								"saveVideoToPhotosAlbum:fail auth deny" === err.errMsg && uni.openSetting({
									
									success: function (sres) {
										if (!sres.authSetting['scope.writePhotosAlbum']  || !res.authSetting['scope.album']) {
										  uni.authorize({
											scope: 'scope.album',
											success(settingdata) {
											  //用户打开了保存图片授权开关
											  that.saveVideo(filePath);
											},
											// // 拒绝授权时，则进入手机设置页面，可进行授权设置
											fail(error) {
											  uni.openSetting({
												success: function (data) {
												  //用户打开了保存图片授权开关
												  that.saveVideo(filePath);
												},
												fail: function (data) {
												}
											  });
											}
						
										  });
										} else {
										  // 已授权则直接进行保存图片
										  //用户打开了保存图片授权开关
										  that.saveVideo(filePath);
										}
									}
								})
				
							},
							complete: function(dc) {
							}
						});
					}
				});
			},
			
			saveImage:function(filePath){
				let that = this;
				uni.saveImageToPhotosAlbum({
					filePath: filePath,
					success: function(data) {
						//执行设置缓存方法
						uni.showToast({
							title: '保存成功',
							icon: "success",
							duration: 2000,
							success() {
								
							}
						});
					}
				});
			},
			/**
			 * @param {Object} e 封面
			 */
			saveNocoverImage:function(e){
				var that = this;
				
				let photourl = this.domain[0].value + this.resultObj.coverSrc;
				
				console.log(this.resultObj.coverSrc);
				
				let fileName = new Date().valueOf();

				let  sysPath = wx.env.USER_DATA_PATH + '/' + fileName + '.jpg';
				
				uni.downloadFile({
					url: photourl,
					filePath: sysPath,
					success: function(downSucc) {
						let filePath = downSucc.filePath;
						uni.showLoading({
							title: '保存中',
							duration: 3000
						});
						uni.saveImageToPhotosAlbum({
							filePath: filePath,
							success: function(succ) {
								uni.showToast({
									title: '保存成功',
									icon: "success",
									duration: 2000,
									success() {
									}
								});
							},
							fail: function(derr) {
								
								if ("saveImageToPhotosAlbum:fail cancel" === derr.errMsg) {
									uni.hideLoading();
									return;
								}
								
								if(derr.errMsg){
									console.log("保存失败，进入授权了");
									uni.openSetting({
										success: function (res) {
											console.log("保存失败，进入授权了-2");
										  uni.authorize({
											scope: 'scope.album',
											success(settingdata) {
											  //用户打开了保存图片授权开关
											  that.saveImage(filePath);
											  console.log("进入授权了-3");
											},
											fail(error) {
												  uni.openSetting({
													success: function (data) {
													  //用户打开了保存图片授权开关
													  that.saveImage(filePath);
													},
													fail: function (data) {
													}
												  });
											}
													
										  });
										  },
										  fail: (openErr) => {
										  },
									});
								}
								uni.hideLoading();
							},
							complete: function(dc) {
							}
						});
						//延迟
					},
					fail: function(data) {
						console.log(data);
						uni.hideLoading();
						uni.showModal({
							title:'提示',
							content:'图片下载失败，请联系平台管理员'
						})
					}
				});
			},
			
			downFile:function(e){
				
				let self = this;
				
				let type = e.currentTarget.dataset.type;
				
				if(type == 1){
					
					let content = '还没有看完广告,一天仅需看'+self.baseInfo.adCount+'次广告当天可免除广告下载'
					
					if(self.baseInfo.showAd == 1){
						uni.showModal({
							title:'提示',
							content: content,
							cancelText: "取消", // 取消按钮的文字  
							confirmText: "确认", // 确认按钮的文字  
							success(res) {
								if(res.confirm){
									let adCount = self.baseInfo.adCount; //每日广告次数
									var openAdLogs = uni.getStorageSync('openAdLogs');
											
									var atdate = new Date();
									atdate = atdate.getFullYear() + "-" + (atdate.getMonth() + 1) + '-' + atdate.getDate();
												
									if (undefined == openAdLogs || openAdLogs.length <= 0) { //缓存不存在
										if(self.baseInfo.showAd == 1){
										  self.readMore();
										}else{
										  self.saveNoMarkVideo();
										}
									}else{
										//缓存存在 是同一天
										if (openAdLogs[0].date == atdate) {
											
											if(parseInt(openAdLogs[0].num) < adCount){
												//显示广告
												if(self.baseInfo.showAd == 1){
												  self.readMore();
												}else{
												  self.saveNoMarkVideo();
												}
											}else{
												self.saveNoMarkVideo();
											}
										}else{
											//缓存存在，并非同一天
											if(self.baseInfo.showAd == 1){
											  self.readMore();
											}else{
											  self.saveNoMarkVideo();
											}
										}
										
									}
								}
							}
						})
					}else{
						self.saveNoMarkVideo();
					}
					
				}else{
					this.saveNocoverImage();
				}
				
			},
			
			//设置缓存  下载缓存
			setDownCache:function(){
				console.log("视频下载");
				var that = this;
				
				let adCount = that.adCount;
				
				var nowDate = new Date();
				nowDate = nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + '-' + nowDate.getDate();
				var openAdLogs = [];
				
				let adLogs = uni.getStorageSync("openAdLogs");
									  
				if(undefined == adLogs || adLogs.length <= 0){
					//缓存不存在
					var log = {
						"date": nowDate,
						"num": 1,
					}
					openAdLogs[0] = log;
					uni.setStorageSync('openAdLogs', openAdLogs);
				}else{
					//同一天相加
					if (adLogs[0].date == nowDate) {
						//如果已经看完不在累加
						let num = adLogs[0].num >= adCount ? adLogs[0].num : adLogs[0].num + 1;
						var log = {
							"date": nowDate,
							"num": num,
						}
						openAdLogs[0] = log;
						uni.setStorageSync('openAdLogs', openAdLogs);
					}else{
						//缓存存在，不是同一天，数量从1开始
						var log = {
							"date": nowDate,
							"num": 1,
						}
						openAdLogs[0] = log;
						uni.setStorageSync('openAdLogs', openAdLogs);
					}
				}
			},
			
			// 打开激励视频
			readMore: function() {
				if (rewardedVideoAd) {
					rewardedVideoAd.show().catch(err => {
						// 失败重试
						rewardedVideoAd.load().then(() => rewardedVideoAd.show())
					})
				}
			},
			
			//加载广告
			loadInterstitialAd: function() {
				var that = this;
				if (uni.createRewardedVideoAd) {
					rewardedVideoAd = uni.createRewardedVideoAd({
						adUnitId: that.setAD.rewardedVideoid,
					});
					  try{
						  if(rewardedVideoAd.closeHandler){
							rewardedVideoAd.offClose(rewardedVideoAd.closeHandler);
							console.log("rewardedVideoAd.offClose卸载成功");
						  }
					  } catch (e) {
						  console.log("rewardedVideoAd.offClose 卸载失败");
					  }
					  rewardedVideoAd.closeHandler= function (res) {
						  // 正常播放结束，可以下发游戏奖励
						  // 用户点击了【关闭广告】按钮
						  if (res && res.isEnded) {
							// 正常播放结束，可以下发游戏奖励
							console.log("播放完毕   1");
							that.saveNoMarkVideo();
							that.setDownCache();
						  } else {
							//提前关闭小程序
							 console.log("播放完毕   未完成");
						  }
						 
					  };
					  rewardedVideoAd.onClose(rewardedVideoAd.closeHandler);
					}
				},
		}
	}
</script>

<style>
	
	
	page{
		background-color: #FFFFFF;
	}
	.href{
		background-color: #FFFFFF;
		margin-top: -10px;
	}
	.input{
		width: 90%;
		margin-left: 15px;
	}
	
	.button-guoshao{
		width: 90%;
	}
	.video_parse{
		height: 180px;
	}
	.video{
		width: 750rpx;
		height: 180px;
	}
</style>
